
angular.module('zixys.font',[])

    .service('googleFontsService',['$http','$q', '$rootScope', function ($http, $q, $rootScope) {
        var self = this;
        this.apiKey = 'AIzaSyCVeyYve90dQMv1g5vFcfDG7076WAllEJ4';
        this.sortOpts = [{
            title:'A-Z',
            value:'alpha'
        },{
            title:'Registered Date',
            value:'date'
        },{
            title:'Popularity',
            value:'popularity'
        },{
            title:'Styles Number',
            value:'style'
        },{
            title:'Trending Growth',
            value:'trending'
        }];

        this.getListOfFonts = function(){
            var fonts = '<script src="http://zixys.com/zixys-api/google.fonts.js" type="text/javascript"></script> ',
                timer,
                interval = 500,
                timeout = 5000/interval,
                inc = 0,
                deferred = $q.defer();

            function waitForFonts() {
                if(window.zixysGoogleFonts){
                    clearTimeout(timer);
                    deferred.resolve(window.zixysGoogleFonts);
                }else{
                    inc++;
                    if(inc>timeout){
                        clearTimeout(timer);
                        deferred.reject('Zixys :: google fonts timed out');
                    }
                }
            }

            $('body').append(fonts);
            timer = setInterval(function(){$rootScope.$apply(waitForFonts())},500);

            return deferred.promise;
        };

    }])

    .service('fontsList',[function(){
        this.font = {}
        this.zxNode = null;

        this.$_deploy = function() {
            if(!this.zxNode) return;
            this.zxNode.setData('font',this.font);
        }

        this.$_reset = function(){
            this.font = {};
        }

    }])

    .directive('googleFonts',['$rootScope', 'googleFontsService', function( $rootScope, googleFontsService ){
        return {
            restrict: 'A',
            replace: true,
            template : '<span><input ng-disabled="disabled" type="button" value="Browse..." /></span>',
            scope : {
                output : '=googleFonts',
                disabled : '=ngDisabled'
            },

            link: function($scope, element, attrs) {
                element.click(function(){
                    if($scope.displayPopup){
                        $scope.displayPopup = false;
                    }else{
                        $scope.displayPopup = true;
                        if (!$scope.googleFonts) {
                            $scope.fetchFonts();
                        }
                    }
                    $scope.$digest();
                });
            },

            controller: ['$scope','$compile','$interpolate', 'googleFontsService', function($scope, $compile, $interpolate, googleFontsService){
                var fontsUL,
                    popup = '<div class="zixys-popup" ng-show="displayPopup">' +
                        '<div class="zixys-pp-title">' +
                        'Google Fonts ({{pagination.totalItems}} fonts, page {{pagination.currentPage}} of {{pagination.totalPages}})'+
                        '<b ng-click="close()">Close</b>'+
                        '</div>'+
                        '<div class="zixys-pp-cont">' +
                        '<i class="z-load" ng-show="isLoading">Loading...</i>'+
                        '<ul class="zixys-pp-list"></ul>'+
                        '</div>'+
                        '<div class="zixys-pp-sort">' +
                        '<div>Sort by:</div>'+
                        '<select ng-model="sortBy" ng-options="key.value as key.title for key in sortOpts">'+
                        '</select>'+
                        '</div>'+
                        '<div pagination="pagination"></div>' +
                        '</div>',
                    styleNode = $('<style></style>'),
                    templateLI = '<li font-index="{{tempIndex}}">' +
                        '<div class="font-title">font : {{tempFont.family}};</div>'+
                        '<div class="font-sample" style="font-family:{{tempFont.family}}">{{sampleText}}</div>' +
                        '</li>',
                    cacheLi = {},
                    styleTemplate = '@font-face { font-family: {{tempFont.family}}; src: url({{tempFont.files.regular}}); }',
                    listContainer;

                $scope.sortOpts = googleFontsService.sortOpts;
                $scope.pagination = {};
                $scope.displayPopup = false;
                $scope.sortBy = 'alpha';

                popup = $compile(popup)($scope);
                popup.appendTo($scope.$root.$contentWrapper);
                styleNode.appendTo($scope.$root.$contentWrapper);
                listContainer = popup.find('div.zixys-pp-cont');

                fontsUL = popup.find('ul.zixys-pp-list');

                fontsUL.click(function(event){
                    $scope.selectFont( $(event.target).parent().attr('font-index'));
                })

                $scope.close = function(){
                    $scope.displayPopup = false;
                }

                $scope.displaySet = function(startAt, howMany) {
                    //hide previews list
                    fontsUL.children().hide();

                    //display new list
                    for(var i = startAt; i<startAt + howMany; i++){
                        if (cacheLi[i]) {
                            cacheLi[i].show();
                        }else{
                            $scope.tempIndex = i;
                            $scope.tempFont = $scope.googleFonts.items[i];
                            cacheLi[i] = $($interpolate(templateLI)($scope));
                            fontsUL.append( cacheLi[i] );
                            styleNode.append( $interpolate(styleTemplate)($scope) );
                        }
                    }
                }

                $scope.sampleText = 'Lorem Ipsum';

                $scope.fetchFonts = function(){
                    $scope.isLoading = true;
                    googleFontsService.getListOfFonts().then(function(fonts){
                        $scope.googleFonts = fonts;
                        $scope.isLoading = false;
                        $scope.pagination.totalItems = fonts.items.length;
                    });
                }

                $scope.pagination.loadSet = function(from, to) {
                    $scope.displaySet(from, to);
                    listContainer[0].scrollTop = 0;
                }

                $scope.selectFont = function(index) {
                    if(!index) return;
                    index = parseInt(index);
                    if(!isNaN(index) && angular.isNumber(index)) {
                        $scope.output = $scope.googleFonts.items[index];
                        $scope.$apply('output');
                    }
                }

            }]
        }
    }])


    .directive('fontTab',function(){
        return {
            restrict: 'C',
            replace: false,
            template:
                    '<div id="zixys-background-tab" >'+

                        '<div class="zixys-inner-tab long-block" src="zixys-text">'+
                            '<div>Text</div>'+
                            '<div>Font</div>'+
                            '<div>External Source</div>'+
                        '</div>'+

                        '<div id="zixys-text">'+
                            '<div>'+
                                '<div class="zixys-menu-block">'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">color</span><input colorpick="fontsList.font.color" ng-disabled="noElement" /></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">Align</span><input ng-model="fontsList.font.textAlign" predefined="textAlign" ng-disabled="noElement" /></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">decoration</span><input ng-model="fontsList.font.textDecoration"  predefined="textDecoration" ng-disabled="noElement" /></div>'+
                                '</div>'+
                                '<div class="zixys-menu-block">'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">overflow</span><input ng-model="fontsList.font.textOverflow" predefined="textOverflow" ng-disabled="noElement" /></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">transform</span><input ng-model="fontsList.font.textTransform" predefined="textTransform" ng-disabled="noElement" /></div>'+
                                '</div>'+
                            '</div>'+
                            '<div>'+
                                '<div class="zixys-menu-block">'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">font weight</span><input ng-model="fontsList.font.fontWeight" predefined="fontWeight" ng-disabled="noElement" /></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">font variant</span><input ng-model="fontsList.font.fontVariant" predefined="fontVariant" ng-disabled="noElement" /></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">font style</span><input ng-model="fontsList.font.fontStyle" predefined="fontStyle" ng-disabled="noElement" /></div>'+
                                '</div>'+
                                '<div class="zixys-menu-block">'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">font family</span><input ng-model="fontsList.font.fontFamily" type="text" ng-disabled="noElement" /></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">font size</span><input ng-model="fontsList.font.fontSize" type="text" class="zixys-spinner" ng-disabled="noElement" /></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">line height</span><input ng-model="fontsList.font.lineHeight" type="text" class="zixys-spinner" ng-disabled="noElement" /></div>'+
                                '</div>'+
                            '</div>'+
                            '<div>' +
                                '<div class="zixys-menu-block">'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">Google Fonts</span><input ng-disabled="noElement" type="button" google-fonts="googleFont" ></div>'+
                                '</div>'+
                                '<div class="zixys-menu-block">'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">font family</span><span class="zixys-menu-textval" ng-bind="fontsList.font.fontFamily"></span></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">subsets</span><span class="zixys-menu-textval" ng-repeat="n in fontsList.font.externalFont.subsets">{{n}}</span></div>'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">variants</span><span class="zixys-menu-textval" ng-repeat="n in fontsList.font.externalFont.variants">{{n}}</span></div>'+
                                '</div>'+
                                '<div class="zixys-fonts-url">'+
                                    '<div class="zixys-input-box"><span class="zixys-menu-label">url</span><textarea class="zx-furl-text" ng-bind="fontsList.font.fontUrl" readonly="readonly"></textarea></div>'+
                                '</div>'+
                            '</div>'+
                        '</div>'+
                        '<div class="zixys-template-action">'+
                            '<input type="button" value="Revert" />'+
                        '</div>'+
                    '</div>',

            controller : ['$scope','fontsList','zxNodes', function ($scope, fontsList,zxNodes) {
                $scope.noElement = true;
                $scope.fontsList = fontsList;
                $scope.zxNodes = zxNodes;

                function draw () {
                    fontsList.$_deploy();
                };

                $scope.$watch('zxNodes.selected',function(zixysNode){
                    if(zixysNode){
                        fontsList.zxNode = zixysNode;
                        $scope.noElement = false;

                        if(zixysNode.data && zixysNode.data.font){
                            fontsList.font = zixysNode.data.font;
                        } else {
                            fontsList.$_reset();
                        }
                    } else {
                        fontsList.zxNode = null;
                        $scope.noElement = true;
                    }
                })

                $scope.$watch('googleFont',function(font) {
                    if (font) {
                        fontsList.font.externalFont = font;
                        fontsList.font.fontFamily = font.family;
                        fontsList.font.fontUrl = '@import url(http://fonts.googleapis.com/css?family="'+font.family.replace(/\s+/g,'+')+'");';
                    }
                });

                $scope.$watch('fontsList.font',function(newVal,oldVal){
                    if(newVal === oldVal) return;
                    draw();
                },true);

            }]
        }
    })
    
    .run(['$rootScope','registerCompiler',function($rootScope,registerCompiler) {

        registerCompiler({
            name:'font',
            compile : function(data) {
                var output = {},key,dashKey;
                    for(var key in data) {
                        dashkey = key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
                        if(data[key]){
                            output[dashkey] = data[key];
                        }
                    }
                return output;
            }
        });

        $rootScope.$on('zixysDomReady',function(event,params){
            $rootScope.addTab('Font','font-tab');
        });
        
    }]);
    
    